// Components/poster/index.js
import {
  Get,
  Post,
  JsonPost
} from "../../utils/request.js"
Component({
  /**
   * 组件的属性列表
   */
  properties: {
    goodsId: {
      type: String,
      value: ''
    },
    baseInfo: {
      type: Object,
      value: {}
    },
    backgImg: {
      type: String,
      value: ''
    },
    share: {
      type: String,
      value: ''
    },
  },

  /**
   * 组件的初始数据
   */
  data: {
    // 小程序码
    DRsrc: '',
    info: {},
    //店铺id
    goodsId: '',
    // 展示海报
    show: false,
    // 商品图片地址
    propic: '',
    // 小程序码地址
    qCord: '',
    windowW: 278,
    windowH: 356,
    shareImage: '',
    avatarUrl: '',
    // 海报地址
    postUrl:''
  },

  /**
   * 组件的方法列表
   */
  methods: {
    close() {
      this.setData({
        show: false
      })
      console.log(this.data.show);

    },
    creat() {
      let that=this
      wx.showLoading({
        title: '生成海报中~',
      })
      // this.setData({
      //   goodsId: "pages/cardDetail/cardDetail?pcid=" + this.properties.goodsId+'&shareUser='+this.properties.share,
      //   info: this.properties.baseInfo
      // })
      wx.getSystemInfo({
        success: function (res) {
          that.setData({
            windowW: res.windowWidth,
            windowH: res.windowHeight
          })
        },
      })
      JsonPost('user/wx-share',{'goods_id':this.data.goodsId}).then(res=>{
        JsonPost('user/get-poster',{'code_url':res.data,'goods_id':this.data.goodsId}).then(res=>{
          that.getBG(res.data).then(res=>{
            that.setData({
              postUrl:res,
              bgpic:res,
            })
            console.log(res);
            
            that.drawCanvas()
          })
        })
      })
      // this.getAccessToken()
      // this.getQrCode_A()
    },
    getAccessToken() {
      //获取accessToken
      let that = this;
      const APP_ID = 'wx5fd8387bfd59c75c'; // 小程序appid
      const APP_SECRET = 'da78e72217e9e8d0571ab20931edfd10'; // 小程序app_secret
      let access_token = '';
      wx.request({
        url: "https://api.weixin.qq.com/cgi-bin/token",
        data: {
          grant_type: 'client_credential',
          appid: APP_ID,
          secret: APP_SECRET
        },
        success: function (res) {
          access_token = res.data.access_token;

          // 接口A：适用于需要的码数量较少的业务场景 生成的是小程序码
          that.getQrCode_A(access_token);

          // 接口B：适用于需要的码数量极多的业务场景 生成的是小程序码
          // that.getQrCode_B(access_token);

          // 接口C：适用于需要的码数量较少的业务场景 生成的是小程序二维码
          // that.getQrCode_C(access_token);
        }
      })
    },
    //获取二维码
    getQrCode_A(access_token) {
      var self = this;
      JsonPost("v2_1/cms/appletqrc/getappletqrc", {
        "path": this.data.goodsId
      }).then(respons => {
        // wx.request({
        //   url: "https://api.weixin.qq.com/wxa/getwxacode?access_token=" + access_token,
        //   method: 'POST',
        //   responseType: 'arraybuffer', //设置响应类型
        //   data: {
        //     // 必须是已经发布的小程序存在的页面（否则报错）
        //     path: 'pages/goodsDetail/goodsDetail?goodsId=' + this.data.goodsId,
        //     width: 298,
        //     auto_color: false, // 自动配置线条颜色，如果颜色依然是黑色，则说明不建议配置主色调
        //     line_color: {
        //       "r": "0",
        //       "g": "0",
        //       "b": "0"
        //     } // auto_color 为 false 时生效，使用 rgb 设置颜色 例如 {"r":"xxx","g":"xxx","b":"xxx"} 十进制表示
        //   },
        //   success: function (respons) {
        // if (respons.error_code != 2000) {
        //   wx.showToast({

        //     title: respons.error_message,

        //     icon: 'none',

        //     duration: 2000

        //   })
        //   return
        // }
        self.setData({
          DRsrc: wx.arrayBufferToBase64(respons.data)
        })
        // console.log(wx.arrayBufferToBase64(respons.data));
        // console.log(respons.data);
        var that = self

        wx.getSystemInfo({

          success: function (res) {

            that.setData({

              windowW: res.windowWidth,

              windowH: res.windowHeight

            })

          },

        })

        // 获取设备宽高，以备海报全屏显示

        // 海报背景图线上地址

        var url = that.data.postUrl

        // 商品图片（哪吒头像）线上地址

        var urll = that.data.backgImg

        // 小程序二维码

        var urlqCord = respons.data
        // var urlqCord = wx.arrayBufferToBase64(respons.data)

        that.getBG(url).then(function (locationData) {

          that.setData({

            bgpic: locationData

          })

          that.getBG(urll).then(function (locationData) {

            that.setData({

              propic: locationData

            })
            var imgSrc = urlqCord
            var save = wx.getFileSystemManager();
            var number = Math.random();
            save.writeFile({
              filePath: wx.env.USER_DATA_PATH + '/pic' + number + '.png',
              data: imgSrc,
              // encoding: 'utf-8',
              encoding: 'base64',
              success: res => {
                wx.saveImageToPhotosAlbum({
                  filePath: wx.env.USER_DATA_PATH + '/pic' + number + '.png',
                  success: function (res) {
                    that.setData({
                      qCord: wx.env.USER_DATA_PATH + '/pic' + number + '.png'
                    })
                    wx.downloadFile({
                      url: JSON.parse(wx.getStorageSync('userInfo')).avatarUrl,
                      success(res) {
                        that.setData({
                          avatarUrl: res.tempFilePath,
                          show: true
                        })
                        that.drawCanvas()
                      }
                    })
                  },
                  fail: function (err) {
                    console.log(err)
                  }
                })
                console.log(res)
              },
              fail: err => {
                console.log(err)
              }
            })

          })

        })

      })
      //   }
      // })
    },

    // 绘制canvas

    drawCanvas() {

      var that = this

      var windowW = that.data.windowW

      var windowH = that.data.windowH

      var text = '从不拘泥任何世俗凡人的目光，我要奔向前方那光芒，生而为魔，那又如何'

      // 使用 wx.createContext 获取绘图上下文 context

      var context = wx.createCanvasContext('firstCanvas', this)

      // 海报背景图

      // console.log(that.data.bgpic, that.data.propic, that.data.qCord);

      context.drawImage(that.data.bgpic, (windowW-278)/2, (windowH-356)/2, 278, 356)


      // 商品图片

      // context.drawImage(that.data.propic, (windowW - 250) / 2, (windowH - 420) / 2, 246, 246)

      // 商品文字描述

      // context.setFontSize(12)

      // context.setFillStyle("#000")

      // context.fillText(that.data.info.goodName, (windowW - 200) / 2, (windowH - 400) / 2,250)
      // var text = that.data.info.goods_name
      // var chr = text.split("");
      // var temp = "";
      // var row = [];
      // context.setFontSize(12)
      // context.setFillStyle("#000")
      // for (var a = 0; a < chr.length; a++) {
      //   if (context.measureText(temp).width < 190) {
      //     temp += chr[a];
      //   } else {
      //     a--;
      //     row.push(temp);
      //     temp = "";
      //   }
      // }
      // row.push(temp);

      //如果数组长度大于2 则截取前两个
      // if (row.length > 2) {
      //   var rowCut = row.slice(0, 2);
      //   var rowPart = rowCut[1];
      //   var test = "";
      //   var empty = [];
      //   for (var a = 0; a < rowPart.length; a++) {
      //     if (context.measureText(test).width < 220) {
      //       test += rowPart[a];
      //     } else {
      //       break;
      //     }
      //   }
      //   empty.push(test);
      //   var group = empty[0] + "..."
      //   rowCut.splice(1, 1, group);
      //   row = rowCut;
      // }
      // for (var b = 0; b < row.length; b++) {
      //   context.fillText(row[b], (windowW - 250) / 2, ((windowH + 120) / 2) + b * 20);
      // }

      // 原价

      // context.setFontSize(13)


      // context.fillText('价值: ￥' + that.data.info.market_price, (windowW - 250) / 2, (windowH + 170) / 2)


      // context.beginPath()
      // context.setLineWidth(1)
      // context.moveTo((windowW - 250) / 2, (windowH + 160) / 2)
      // context.lineTo((windowW - 80) / 2, (windowH + 160) / 2)
      // context.stroke()
      // 价格

      // context.setFontSize(13)


      // context.fillText('现售: ', (windowW - 250) / 2, (windowH + 220) / 2)

      // context.setFontSize(13)

      // context.setFillStyle("red")

      // context.fillText('￥' + that.data.info.shop_price, (windowW - 180) / 2, (windowH + 220) / 2)


      // 识别小程序二维码

      // context.drawImage(that.data.qCord, (windowW + 100) / 2, (windowH + 210) / 2, 75, 75)

      // context.setFillStyle("#000000")

      // context.setFontSize(14)

      // context.fillText('长按识别小程序立即购买', (windowW - 180) / 2, (windowH + 410) / 2)


      // context.drawImage(that.data.avatarUrl, (windowW - 220) / 2, (windowH + 250) / 2, 40, 40)

      // context.setFillStyle("#000000")

      // context.setFontSize(12)

      
      // context.fillText(JSON.parse(wx.getStorageSync('userInfo')).nickName, (windowW - 250) / 2, (windowH + 360) / 2)

      context.draw()
      that.setData({
        show: true
      })
      wx.hideLoading()

    },

    // 点击保存按钮，同时将画布转化为图片

    daochu: function () {
      wx.showLoading({
        title: '加载中',
      })

      var that = this;

      var windowW = that.data.windowW

      var windowH = that.data.windowH

      wx.canvasToTempFilePath({

        x: (windowW - 280) / 2,

        y: (windowH - 450) / 2,

        width:280,
        
        height:450,

        canvasId: 'firstCanvas',

        fileType: 'jpg',

        quality: 1,

        success: function (res) {

          console.log(res.tempFilePath);


          that.setData({

            shareImage: res.tempFilePath

          })

          wx.hideLoading()

          setTimeout(function () {

            wx.showModal({

              title: '提示',

              content: '下载海报',

              success(res) {

                if (res.confirm) {

                  that.eventSave()

                } else if (res.cancel) {

                  console.log('用户点击取消')

                }

              }

            })

          }, 1000)

        },
        fail: err => {
          console.log(err)
        }

      }, this)

    },

    // 将商品分享图片保存到本地

    eventSave() {

      wx.saveImageToPhotosAlbum({

        filePath: this.data.shareImage,

        success(res) {

          wx.showToast({

            title: '保存图片成功',

            icon: 'success',

            duration: 2000

          })

        }

      })

    },

    //将线上图片地址下载到本地，此函数进行了封装，只有在需要转换url的时候调用即可

    getBG(url) {

      // Promise函数给我很大的帮助，让我能return出回调函数中的值

      return new Promise(function (resolve) {

        wx.downloadFile({

          url: url,

          success: function (res) {
            console.log("下载成功", res);

            url = res.tempFilePath

            resolve(url);

          },
          fail(err) {
            console.log(err);
            wx.showModal({
              title: '提示',
              content: '请授权开启相册',
              success(res) {
                if (res.confirm) {
                  console.log('用户点击确定')
                  wx.openSetting({
                    success(settingdata) {
                      console.log(settingdata)
                      if (settingdata.authSetting['scope.writePhotosAlbum']) {
                        wx.showToast({
                          title: '授权成功',
                          icon: 'none',
                          duration: 2000
                        })
                      } else {
                        console.log('获取权限失败，给出不给权限就无法正常使用的提示')
                      }
                    }
                  })
                } else if (res.cancel) {
                  console.log('用户点击取消')
                }
              }
            })
          }

        })

      })

    },

    // canvas多文字换行

    newLine(txt, context) {

      var txtArr = txt.split('')

      var temp = ''

      var row = []

      for (var i = 0; i < txtArr.length; i++) {

        if (context.measureText(temp).width < 210) {

          temp += txtArr[i]

        } else {

          i--

          row.push(temp)

          temp = ''

        }

      }

      row.push(temp)

      //如果数组长度大于3 则截取前三个

      if (row.length > 3) {

        var rowCut = row.slice(0, 3);

        var rowPart = rowCut[2];

        var test = "";

        var empty = [];

        for (var a = 0; a < rowPart.length; a++) {

          if (context.measureText(test).width < 180) {

            test += rowPart[a];

          } else {

            break;

          }

        }

        empty.push(test);

        var group = empty[0] + "..." //这里只显示三行，超出的用...表示

        rowCut.splice(2, 1, group);

        row = rowCut;

      }

      return row

    }
  }
})